<?php


namespace app\api\job;


use app\common\controller\CommonCallpolice;
use app\common\model\Merchant;
use think\Queue;
use think\queue\Job;

class SendNotify
{
    public function task_biz_notify($data = '')
    {
//        $this-> notify_wx(1214);

        // 1.当前任务将由哪个类来负责处理。
        //   当轮到该任务时，系统将生成一个该类的实例，并调用其 fire 方法
        $jobHandlerClassName = 'app\api\job\SendNotify';
        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
        $jobQueueName = "task_biz_notify";
        // 3.当前任务所需的业务数据 . 不能为 resource 类型，其他类型最终将转化为json形式的字符串
        //   ( jobData 为对象时，需要在先在此处手动序列化，否则只存储其public属性的键值对)
        if (is_array($data)) {
            $data = json_encode($data, 256);
        }
        trace( "send_tz_biz:" . json_encode($data,256),'SysRunLog');
        $jobData = $data;
        // 4.将该任务推送到消息队列，等待对应的消费者去执行
        $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);
        // database 驱动时，返回值为 1|false  ;   redis 驱动时，返回值为 随机字符串|false
        if ($isPushed !== false) {
            return 'success';
        } else {
            return 'error';
        }
    }

    public function fire(Job $job, $data)
    {

        $isJobDone = $this->task_notify($data);
        $job->delete();
        if ($isJobDone) {
            //如果任务执行成功， 记得删除任务
            $job->delete();
            return '完成';
        } else {
            if ($job->attempts() > 3) {
                print("<warn>任务已完成3次!" . "</warn>\n");
                $job->delete();
                // 也可以重新发布这个任务
                //print("<info>Hello Jobmach will be availabe again after 2s."."</info>\n");
                //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }



    /**
     * 根据消息中的数据进行实际的业务处理
     * @param array|mixed $data 发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */


    //执行异步通知
    public function task_notify($data)
    {
        $datas = json_decode($data, true);
        if (isset($datas['merchantid'])) {
            $Merchant = new Merchant();
            $notify_url = $Merchant->where('id', $datas['merchantid'])->value('notify_url');
            //$notify_url ="http://property.wunengkeji.com/notify.php/syncnotify";
//            $this-> notify_wx($notify_url);

            if (!empty($notify_url)) {
//               $this-> notify_wx(1213);
                $s = $this->http_post($notify_url, $data);
            }
        }
    }

    private function http_post($url, $param, $post_file = false)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) {
            $is_curlFile = true;
        } else {
            $is_curlFile = false;
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);
            }
        }
        if (is_string($param)) {
            $strPOST = $param;
        } elseif ($post_file) {

            if ($is_curlFile) {
                foreach ($param as $key => $val) {

                    if (substr($val, 0, 1) == '@') {

                        $param[$key] = new \CURLFile(realpath(substr($val, 1)));

                    }
                }

            }
            $strPOST = $param;

        } else {
            $aPOST = array();
            foreach ($param as $key => $val) {
                $aPOST[] = $key . "=" . urlencode($val);
            }
            $strPOST = join("&", $aPOST);

        }

        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('Content-Type:application/json; charset=utf-8',

            'Content-Length: ' . strlen($param)));
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);

        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }
    //错误报警
    public function notify_wx($msg){

        $baseurl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=520b0e11-2dcf-445e-824f-a35fd2d36687";
        $message = $msg;
        $data = array('msgtype' => 'text', 'text' => array('content' => $message,'mentioned_list'=>['@all']));
        $data_string = json_encode($data);
        $result = $this->request_by_curl($baseurl, $data_string);
//        return $result;

    }
    public function request_by_curl($remote_server, $post_string)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
        // curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        // curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    private function profit_account($mid, $price)
    {


    }
}